/*
 * @Author: JanKinCai
 * @Date:   2020-12-24 10:59:37
 * @Last Modified by:   JanKinCai
 * @Last Modified time: 2020-12-24 10:59:37
 */
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:protobuf/protobuf.dart';
import 'package:web_socket_channel/io.dart';

import 'Protocol.pb.dart';
import 'web_socket.dart';
import 'IM.pb.dart';

void test_connect_server() {
  var connectInfo = ConnectMessage.create();
  connectInfo.appKey = 'uxs4jymrs7rb7';
  connectInfo.token = 'wYNxxbh5nslPgoBejqYc+Fc4nmjtTJ8kFp1V0LeM1o8=';
  connectInfo.deviceId = '5d6622157987735c';
  connectInfo.info = 'web|1.0.1|4G';
  connectInfo.isPushDisabled = true;
  connectInfo.packageName = 'com.citylife.websocket';
  connectInfo.pushToken = '';
  var req = IMMessageReq.create();
  req.connect = connectInfo;
  var buffer = req.writeToBuffer();
  // var socket = SocketUtil.generate();
  var host = 'im2.citylife.com';
  // var host = '111.198.84.118';
  var port = 8200;
  SocketUtil.generate(secure: true).connect(host, port, buffer, (result) {
    print(result);
    if (result is Uint8List) {
      var res = IMMessageRes.fromBuffer(result);
      if (res.hasConnectAck()) {
        print(res.connectAck);
      }
    }
  });
  test_timer(10);
}

void test_timer(int second) {
  Timer(Duration(seconds: second), () {
    print('finished.');
  });
}

void test_connect_self_server() {
  const String HOST_NAME = 'localhost';
  const secure = true;
  String localFile(path) => Platform.script.resolve(path).toFilePath();
  SecurityContext serverContext = new SecurityContext()
    ..useCertificateChain(localFile('../lib/certificates/server_chain.pem'))
    ..usePrivateKey(localFile('../lib/certificates/server_key.pem'),
        password: 'dartdart');
  SecurityContext clientContext = new SecurityContext()
    ..setTrustedCertificates(
        localFile('../lib/certificates/trusted_certs.pem'));
  Future<HttpServer> createServer({int backlog: 0}) => secure
      ? HttpServer.bindSecure(HOST_NAME, 0, serverContext, backlog: backlog)
      : HttpServer.bind(HOST_NAME, 0, backlog: backlog);
  HttpClient createClient() =>
      secure ? HttpClient(context: clientContext) : HttpClient();

  createServer().then((server) {
    server.transform(WebSocketTransformer()).listen((socket) {
      socket.listen((message) {
        print("server: $message");
        socket.add(message);
        socket.close(10086);
      }, onDone: () {
        print("server: done");
      }, onError: (error) {
        print('server: $error');
      });
    });

    void clientConnect() {
      var connectInfo = ConnectMessage.create();
      connectInfo.appKey = 'uxs4jymrs7rb7';
      connectInfo.token = 'wYNxxbh5nslPgoBejqYc+Fc4nmjtTJ8kFp1V0LeM1o8=';
      connectInfo.deviceId = '5d6622157987735c';
      connectInfo.info = 'web|1.0.1|4G';
      connectInfo.isPushDisabled = true;
      connectInfo.packageName = 'com.citylife.websocket';
      connectInfo.pushToken = '';
      var req = IMMessageReq.create();
      req.connect = connectInfo;
      var buffer = req.writeToBuffer();
      // var socket = SocketUtil.generate();
      var host = HOST_NAME;
      var port = server.port;
      SocketUtil.generate(secure: secure).connect(host, port, buffer, (result) {
        print(result);
        if (result is Uint8List) {
          var res = IMMessageReq.fromBuffer(result);
          if (res.hasConnect()) {
            print(res.connect);
          }
          server.close();
        }
      });
    }

    clientConnect();
  }).catchError((error) {
    print('$error');
  });
}

void test_connect_other_wss() {
  var host = 'im2.citylife.com';
  var url = 'ws://$host:8200/chat';
  // var url = 'ws://192.168.41.183:30001/chat';
  // var url = 'wss://echo.websocket.org';
  // var headers = {'Pragma': 'no-cache', 'Upgrade': 'websocket'};
  WebSocket.connect(url).then((socket) {
    socket.listen((message) {
      print('$message');
    }, onDone: () {
      print('done:');
    }, onError: (error) {
      print('$error');
    });
    socket.add('hello, I am testing...');
  }).catchError((error) {
    print('$error');
  });
}

void test_websocket_channel() {
  // var host = '111.198.84.118';
  // var host = 'im2.citylife.com';
  var host = '192.168.41.183';
  // var url = 'wss://$host:8200/chat';
  var url = 'ws://$host:30001/chat';
  var channel = IOWebSocketChannel.connect(url);
  channel.stream.listen((message) {
    print('$message');
    // channel.sink.add('client recv data.');
    // channel.sink.close(10086);
  });
  channel.sink.add('client send data.');
  Timer(Duration(seconds: 10), () {
    print('close channel');
    channel.sink.close(10086, 'null');
    // channel.stream.timeout(Duration(seconds: 5), onTimeout: (event) {
    //   print('$event');
    // });
  });
}

void test_websocket_channel_protobuf() {
  // var host = '111.198.84.118';
  var host = 'im2.citylife.com';
  // var host = '192.168.41.183';
  var url = 'wss://$host:8200/chat';
  // var url = 'ws://$host:30001/chat';
  var channel = IOWebSocketChannel.connect(url);
  channel.stream.listen((message) {
    print('$message');
    // channel.sink.add('client recv data.');
    // channel.sink.close(10086);
  }, onDone: () {
    print('done');
  }, onError: (error) {
    print("$error");
  });
  var connectInfo = ConnectMessage.create();
  connectInfo.appKey = 'uxs4jymrs7rb7';
  connectInfo.token = 'wYNxxbh5nslPgoBejqYc+Fc4nmjtTJ8kFp1V0LeM1o8=';
  connectInfo.deviceId = '5d6622157987735c';
  connectInfo.info = 'web|1.0.1|4G';
  connectInfo.isPushDisabled = true;
  connectInfo.packageName = 'com.citylife.websocket';
  connectInfo.pushToken = '';
  var req = IMMessageReq.create();
  req.connect = connectInfo;
  var buffer = req.writeToBuffer();
  channel.sink.add(connectInfo);
  Timer(Duration(seconds: 10), () {
    print('close channel');
    channel.sink.close(10086, 'null');
    // channel.stream.timeout(Duration(seconds: 5), onTimeout: (event) {
    //   print('$event');
    // });
  });
}
